import React from "react";
import {SecurityMenu} from "type/entity/SecurityMenu";
import {DefaultOptionType} from "rc-select/lib/Select";
import {Form, Input, Select, Tag} from "antd";
import useAsyncEffect from "hook/useAsyncEffect";
import RequestHandler from "http/RequestHandler";

const MenuSelectHandler = () => {
    const menuListRef = React.useRef<SecurityMenu[]>([]);
    const [ option, setOption ] = React.useState<DefaultOptionType[]>([]);
    const form = Form.useFormInstance<SecurityMenu>();

    const [ parentPath, setParentPath ] = React.useState<string>("");

    useAsyncEffect(async () => {
        const res = await RequestHandler.get<SecurityMenu[]>("/manager/admin/menu/list/not-last");
        if (!res.success){
            return;
        }
        menuListRef.current = res.data;
        const pid = form.getFieldValue("parentId");
        const op = res.data.map(e => {
            if (e.id === pid){
                setParentPath(e.path);
            }
            return {
                label: e.label,
                value: e.id
            };
        });
        setOption(op);
    });

    const onChange = (value: string) => {
        const find = menuListRef.current.find(e => e.id === Number(value));
        if(find){
            setParentPath(find.path);
        }
    };
    return (
        <>
            <Form.Item<SecurityMenu> label={"父菜单"} name={"parentId"}>
                <Select
                    onChange={onChange}
                    placeholder={`请选择父菜单`}
                    allowClear
                    options={option}
                    loading={option.length === 0}
                />
            </Form.Item>
            <Form.Item<SecurityMenu> name={"path"} label={"菜单路径"} >
                <Input addonBefore={<Tag color={"success"}>{parentPath}</Tag>}/>
            </Form.Item>
        </>
    );
};

export default MenuSelectHandler;